<template>
	<view class="pageContent">
		<view class="memberMain">
			<view class="memberMaTi">选择成员身份</view>
			<view>
				<view class="memberType" :class="{'select' : index==headIndex}" v-for="(item,index) in headList"
					:key="index" @click="selectHead(index)">
					{{item.roleName || '成员身份'}}
				</view>
				<view class="memberType" v-if="0">
					{{'成员身份'}}
				</view>
			</view>
			<view class="memberItem">
				<text class="memberItSt">*</text>
				<view class="memberItTi textJustify">身份证号</view>
				<view class="memberRight">
					<input class="memberItIn" type="idcard" placeholder-class="inputPlaceHold"
						v-model="formData.idCardNumber" :placeholder="placeholderId" maxlength="18" @input="inputChange"
						:disabled="updateFlag" id="idCardNumber" />
				</view>
			</view>
			<view class="memberItem">
				<text class="memberItSt">*</text>
				<view class="memberItTi textJustify">成员真名</view>
				<view class="memberRight">
					<input class="memberItIn" placeholder-class="inputPlaceHold" v-model="formData.name"
						:placeholder="placeholder" :disabled="disabledFlag" />
				</view>
			</view>
			<view class="memberItem">
				<text class="memberItSt">*</text>
				<view class="memberItTi textJustify">性别</view>
				<view class="memberRight">
					<view class="perType" :class="index==perIndex ? 'select' : ''" v-for="(item,index) in perList"
						:key="index" @click="selectPer(index)">
						{{item.name}}
					</view>
				</view>
			</view>
			<view class="memberItem">
				<text class="memberItSt">*</text>
				<view class="memberItTi textJustify">出生年月</view>
				<picker class="comePicRight" mode="date" :value="date" @change="choose" id="deliverTime"
					v-if="!disabledFlag">
					<input class="memberItIn" placeholder-class="inputPlaceHold" v-model="formData.date"
						:placeholder="placeholderAd" disabled="true" />
					<image class="comePicLim" :src="localImages +'/date.png'" mode="scaleToFill" />
				</picker>
				<view class="comePicRight" v-if="disabledFlag">
					<input class="memberItIn" placeholder-class="inputPlaceHold" v-model="date"
						:placeholder="placeholderAd" disabled="true" />
				</view>
				<!-- <view class="memberRight">
            <input class="memberItIn" placeholder-class="inputPlaceHold" v-model="formData.date" :placeholder="placeholderAd" disabled="true"/>
            <picker class="comePicRight" mode="date" :value="date" @change="choose" id="deliverTime" v-if="!disabledFlag">
              <image class="comePicLim" :src="localImages +'/date.png'" @click="selectDate"/>
            </picker>
          </view> -->
			</view>

			<view class="memberItem">
				<text class="memberItSt empty">*</text>
				<view class="memberItTi textJustify">手机号码</view>
				<view class="memberRight">
					<input class="memberItIn" type="number" placeholder-class="inputPlaceHold" v-model="formData.phone"
						:placeholder="placeholderPh" maxlength="11" @input="inputChange" :disabled="disabledFlag"
						id="phone" />
				</view>
			</view>
			<view class="memberItem">
				<text class="memberItSt empty">*</text>
				<view class="memberItTi textJustify">上传证件</view>
				<view class="memberUpload">
					<view @click="imagePhoto" data-type="idCardFrontUrl">
						<image class="memberUpTrueIc" v-if="!idCardFrontUrl" :src="localImages +'/dateTrue.png'" />
						<image class="memberUpTrueIc" v-if="idCardFrontUrl" :src="idCardFrontUrl" />
					</view>
					<view @click="imagePhoto" data-type="idCardBackUrl">
						<image class="memberUpTrueIc" v-if="!idCardBackUrl" :src="localImages +'/dateFalse.png'" />
						<image class="memberUpTrueIc" v-if="idCardBackUrl" :src="idCardBackUrl" />
					</view>
				</view>
			</view>
			<view class="memberItem" v-if="0">
				<text class="memberItSt empty">*</text>
				<view class="memberItTi">上传生活<text>\n&nbsp;&nbsp;&nbsp;照片</text></view>
				<view class="memberUpload">
					<view @click="imagePhoto" data-type="facePictureUrl">
						<view class="memberUpMain" v-if="!facePictureUrl">
							<image class="memberUpMainIm" :src="images +'/facePictureBac.png'" />
							<image class="memberUpMainIc centerAbs" :src="images +'/facePictureIc.png'" />
							<view class="centerAbs memberUpMainTe">上传生活照片</view>
						</view>
						<image class="memberUpTrueIc " v-if="facePictureUrl" :src="facePictureUrl" />
					</view>
				</view>
			</view>

			<view class="memberItem" v-if="headIndex==0 && userMsg.roleId==16">
				<text class="memberItSt empty">*</text>
				<view class="memberItTi">租赁合同</view>
				<view class="memberUploadLea">
					<view class="memberUpLeaMa" @click="imagePhoto" data-type="leaseContractOneUrl">
						<image class="memberUpLea" v-if="!leaseContractOneUrl" :src="images +'/lease1.png'" />
						<image class="memberUpLea" v-if="leaseContractOneUrl" :src="leaseContractOneUrl" />
					</view>
					<view class="memberUpLeaMa" @click="imagePhoto" data-type="leaseContractTwoUrl">
						<image class="memberUpLea" v-if="!leaseContractTwoUrl" :src="images +'/lease2.png'" />
						<image class="memberUpLea" v-if="leaseContractTwoUrl" :src="leaseContractTwoUrl" />
					</view>
					<view class="memberUpLeaMa" @click="imagePhoto" data-type="leaseContractThreeUrl">
						<image class="memberUpLea" v-if="!leaseContractThreeUrl" :src="images +'/lease3.png'" />
						<image class="memberUpLea" v-if="leaseContractThreeUrl" :src="leaseContractThreeUrl" />
					</view>
					<view class="memberUpLeaMa" @click="imagePhoto" data-type="leaseContractFourUrl">
						<image class="memberUpLea" v-if="!leaseContractFourUrl" :src="images +'/lease4.png'" />
						<image class="memberUpLea" v-if="leaseContractFourUrl" :src="leaseContractFourUrl" />
					</view>
				</view>
			</view>
			<view class="memberItem">
				<text class="memberItSt empty">*</text>
				<view class="memberItTi">门禁期限</view>
				<picker class="comePicRight" mode="date" :value="dateLim" @change="chooseLim">
					<input class="memberItIn" placeholder-class="inputPlaceHold" v-model="dateLim"
						:placeholder="placeholder5" disabled="true" />
					<image class="comePicLim" :src="localImages +'/date.png'" mode="scaleToFill" />
				</picker>
			</view>
			<view class="memberItem">
				<text class="memberItSt empty">*</text>
				<view class="memberItTi textJustify">留言</view>
				<view class="memberRight">
					<input class="memberItIn" placeholder-class="inputPlaceHold" v-model="formData.applyReason"
						placeholder="请填写留言" maxlength="30" />
				</view>
			</view>
			<view class="memberItem" v-if="0">
				<text class="memberItSt empty">*</text>
				<!-- 这里不能出现人脸字段，不然发布小程序会审核失败 -->
				<view class="memberItTi textJustify">开门功能</view>
				<view class="memberRight">
					<image class="switchImg" v-if="!formData.facePictureUrl" :src="images +'/switchOff.png'"
						mode="widthFix" @click="imagePhoto" data-type="facePictureUrl" />
					<image class="switchImg" v-if="formData.facePictureUrl" :src="images +'/switchOn.png'"
						mode="widthFix" @click="facePictureClear" />
				</view>
			</view>
			<button class="btOne" @click="commitTamp" :class="headIndex==-1 ? 'btDefault' : ''">提交</button>
		</view>

	</view>
</template>

<script>
	import config from '../../static/config.js'
	import util from '../../static/utils/util.js'
	export default {
		data() {
			return {
				images: config.images,
				localImages: config.localImages,
				password: '',
				headList: [{
						value: 0,
						name: '租户',
					},
					{
						value: 2,
						name: '父母',
					},
					{
						value: 3,
						name: '小孩',
					},
					{
						value: 3,
						name: '朋友',
					},
					{
						value: 3,
						name: '朋友',
					},
				],
				headIndex: -1,
				perList: [{
						value: 0,
						name: '男',
					},
					{
						value: 1,
						name: '女',
					},
				],
				perIndex: 0,
				formData: {
					roleId: "",
					name: "",
					idCardNumber: "",
					sex: 0,
					date: "",
					phone: "",
					dateLim: "",
				},
				idCardFrontUrl: '',
				idCardBackUrl: '',
				facePictureUrl: '',
				leaseContractOneUrl: '',
				leaseContractTwoUrl: '',
				leaseContractThreeUrl: '',
				leaseContractFourUrl: '',
				placeholder: '请填写身份证上的真实姓名',
				placeholderAd: '请选择出生年月',
				placeholderId: '请填写有效身份证号码',
				placeholderPh: '请填写手机号',
				placeholder5: '请选择门禁失效日期',
				date: '',
				dateLim: '',
				previous: '',
				disabledFlag: false, //禁止修改字段的标记
				userMsg: '',
				updateFlag: false, //修改成员的标记
				initPhone: '', //修改成员-初始手机号
			}
		},

		async onLoad(options) {
			var userMsg = wx.getStorageSync('userMsg');
			this.userMsg = userMsg;
			//修改成员
			if (options.json) {
				var title = '修改成员'
				this.updateFlag = true;
				var param = JSON.parse(options.json)
				console.log('param', param)
				Object.assign(this.formData, param)
				//添加id
				this.formData['id'] = param.ownerId
				this.updateParam(param);
				await this.headListGet();
				//判断成员身份
				this.headList.forEach((item, index) => {
					if (item.roleId == param.roleId) {
						this.headIndex = index;
						console.log('this.headIndex', this.headIndex, index)
					}
				})
				this.modifyParam(param);
				//存储初始手机号
				if (param.telephone) {
					this.initPhone = param.telephone
				}
			} else {
				var title = '添加成员'
				this.updateFlag = false;
				//添加申请人的id参数
				var room = wx.getStorageSync('room');
				var param = {
					roomIdNow: room.roomId,
					projectId: room.projectId,
				}
				Object.assign(this.formData, param)
				this.headListGet().then(() => {
					this.selectHead(0) //默认选择第一个选项
				});
			}
			wx.setNavigationBarTitle({
				title: title
			})

		},

		onShow() {},

		onUnload() {
			this.reset()
		},

		methods: {
			async inputChange(e) {
				console.log(e)
				var value = e.detail.value;
				var key = e.currentTarget.id;
				// if(this.updateFlag){ //修改直接返回
				//   return;
				// }
				if (key == 'idCardNumber') {
					//查询系统是否有身份证信息
					if (value.length == 18) {
						var params = {
							idCardNumber: value,
						}
						this.ownerInfo(params, 1)
					}
					//清空之前回填的信息，防止通过手机号修改原有用户的信息
					if (value.length == 17 && this.disabledFlag) {
						this.reset();
						this.formData.idCardNumber = value;
					} else {
						this.disabledFlag = false;
					}
					console.log('disabledFlag', this.disabledFlag)
				}
				if (key == 'phone') {
					//查询系统是否有重复手机号
					if (value.length == 11) {
						//修改成员-手机号没有发生变化，不查询接口
						if (this.initPhone == value) {
							return
						}
						var params = {
							telephone: value,
						}
						this.ownerInfo(params, 2)
					}
				}
			},

			async ownerInfo(params, flag) {
				var url = '/UserServer/owner/info/ownerInfo'
				var options = {
					url,
					params
				}
				var param = await util.requestPro(options);
				if (flag == 1) {
					if (param.idCardNumber) {
						//自动回填用户信息，并且不允许修改其他必填信息
						this.updateParam(param);
						this.disabledFlag = true;
					} else {
						this.disabledFlag = false;
					}
				}
				if (flag == 2) {
					//手机号已经存在,请重新输入,不然提交表单后会替换他人信息
					if (param.idCardNumber) {
						wx.showToast({
							title: '当前手机号已经存在，请重新输入',
							icon: 'none',
							duration: 1500,
						})
						this.formData.phone = ""
					}
				}
			},

			//回显用户基本信息
			updateParam(param) {
				this.formData.phone = param.telephone;
				this.formData.name = param.name;
				this.formData.date = param.birthday;
				this.date = param.birthday;
				this.dateLim = param.expireDate || ''; //不存在就传空
				//判断性别
				this.perList.forEach((item, index) => {
					if (item.value == param.sex) {
						this.perIndex = index;
						console.log('this.perIndex', this.perIndex, index)
					}
				})
			},

			reset() {
				this.formData = {
					roleId: "",
					name: "",
					idCardNumber: "",
					sex: 0,
					date: "",
					phone: "",
					dateLim: "",
				};
				this.headIndex = -1;
				this.perIndex = 0;
				this.date = "";
				this.dateLim = "";
				this.disabledFlag = false;
				this.idCardFrontUrl = ''
				this.idCardBackUrl = ''
				this.facePictureUrl = ''
				this.leaseContractOneUrl = ''
				this.leaseContractTwoUrl = ''
				this.leaseContractThreeUrl = ''
				this.leaseContractFourUrl = ''
			},

			chooseLim(e) {
				console.log('chooseLim', e)
				this.dateLim = e.detail.value
				this.formData.dateLim = e.detail.value
			},
			choose(e) {
				console.log('choose', e)
				this.date = e.detail.value
				this.formData.date = e.detail.value
			},

			selectHead(index) {
				this.headIndex = index;
				this.formData.roleId = this.headList[index].roleId;
			},
			selectPer(index) {
				if (this.disabledFlag) return;
				this.perIndex = index;
			},

			async headListGet() {
				var url = '/UserServer/owner/info/roleName'
				var options = {
					url,
					params: {}
				}
				var param = await util.requestPro(options);
				//租客不显示租客
				if (this.userMsg.roleId == 17) {
					param.shift();
				}
				this.headList = param
			},

			//修改用户，显示图片信息
			modifyParam(param) {
				if (param.idCardFrontUrl) {
					this.formData.idCardFrontUrl = param.idCardFrontUrl;
					this.idCardFrontUrl = config.IMAGE_APIHOST + param.idCardFrontUrl;
				}
				if (param.idCardBackUrl) {
					this.formData.idCardBackUrl = param.idCardBackUrl;
					this.idCardBackUrl = config.IMAGE_APIHOST + param.idCardBackUrl;
				}
				if (param.facePictureUrl) {
					this.formData.facePictureUrl = param.facePictureUrl;
					this.facePictureUrl = config.IMAGE_APIHOST + param.facePictureUrl;
				}
				if (param.leaseContractOneUrl) {
					this.formData.leaseContractOneUrl = param.leaseContractOneUrl;
					this.leaseContractOneUrl = config.IMAGE_APIHOST + param.leaseContractOneUrl;
				}
				if (param.leaseContractTwoUrl) {
					this.formData.leaseContractTwoUrl = param.leaseContractTwoUrl;
					this.leaseContractTwoUrl = config.IMAGE_APIHOST + param.leaseContractTwoUrl;
				}
				if (param.leaseContractThreeUrl) {
					this.formData.leaseContractThreeUrl = param.leaseContractThreeUrl;
					this.leaseContractThreeUrl = config.IMAGE_APIHOST + param.leaseContractThreeUrl;
				}
				if (param.leaseContractFourUrl) {
					this.formData.leaseContractFourUrl = param.leaseContractFourUrl;
					this.leaseContractFourUrl = config.IMAGE_APIHOST + param.leaseContractFourUrl;
				}
			},

			//图片上传
			imagePhoto(e) {
				var e = e.mp;
				var type = e.currentTarget.dataset.type;
				var self = this;
				wx.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success(res) {
						const tempFilePaths = res.tempFilePaths
						var src = res.tempFilePaths[0];
						util.uploadFile(src).then((res) => {
							var param = res;
							//测试环境取服务器地址
							// if(config.isRelease){
							//   var url=param.url
							// }else {
							//   //本地环境取本地地址
							//   var url=config.IMAGE_APIHOST
							// }
							var urlPath = param.url + param.filePath;
							if (type == 'idCardFrontUrl') {
								self.idCardFrontUrl = urlPath;
								self.formData[type] = param.filePath;
							} else if (type == 'idCardBackUrl') {
								self.idCardBackUrl = urlPath;
								self.formData[type] = param.filePath;
							} else if (type == 'facePictureUrl') {
								self.facePictureUrl = urlPath;
								self.formData[type] = param.filePath;
							} else if (type == 'leaseContractOneUrl') {
								self.leaseContractOneUrl = urlPath;
								self.formData[type] = param.filePath;
							} else if (type == 'leaseContractTwoUrl') {
								self.leaseContractTwoUrl = urlPath;
								self.formData[type] = param.filePath;
							} else if (type == 'leaseContractThreeUrl') {
								self.leaseContractThreeUrl = urlPath;
								self.formData[type] = param.filePath;
							} else if (type == 'leaseContractFourUrl') {
								self.leaseContractFourUrl = urlPath;
								self.formData[type] = param.filePath;
							}
						})
					}
				})
			},

			facePictureClear() {
				this.facePictureUrl = ''
				this.formData['facePictureUrl'] = ''
			},

			commitTamp() {
				util.tottleOne(() => {
					this.submit()
				})
			},

			async submit() {
				var status = this.validation() || false;
				if (status) {
					//获取业主该手机号绑定的房屋列表
					var params = this.formData;
					params.sex = this.perList[this.perIndex].value;
					params['expireDate'] = this.dateLim;
					params['birthday'] = params.date;
					params['telephone'] = params.phone || ''; //手机号选填
					// var params={"name":"aa11","idCardNumber":"430406202101011031","telephone":"13012345681","sex":1,"birthday":"1993-7","roomIdNow":"16","projectId":"1","expireDate":"2088-12-31","roleId":"17"}
					console.log('submit=params', params)
					var method = "POST"
					if (this.updateFlag) {
						method = "PUT"
					}
					//判断选择的日期是否有效
					if (util.compareNowDate(this.dateLim)) {
						return;
					}
					var url = '/UserServer/owner/info/ownerInfo'
					var options = {
						url,
						params,
						method,
					}
					try {
						await util.requestPro(options)
					} catch (e) {
						console.log('catch=ownerInfo', e)
						if (e.status == 500) {
							if (this.disabledFlag) {
								wx.showToast({
									title: '当前房屋已经绑定该身份证，请勿重复添加',
									icon: 'none'
								})
							}
							//没有填写手机号
							else if (!this.formData.telephone) {
								wx.showToast({
									title: '请填写手机号',
									icon: 'none'
								})
							}
						}
						return;
					}
					var title = "添加成功"
					if (this.updateFlag) {
						title = "修改成功"
						if (this.userMsg.roleId == 17) {
							title = "修改已提交，请等待审核"
						}
					}
					wx.showToast({
						title: title,
						icon: 'none'
					})
					setTimeout(() => {
						wx.navigateBack({
							delta: 1
						})
					}, 700)
				}
			},

			validation() {
				if (this.formData.roleId === '') {
					wx.showToast({
						title: "请选择成员身份",
						icon: 'none'
					});
					return false;
				}
				if (this.formData.idCardNumber == '') {
					wx.showToast({
						title: this.placeholderId,
						icon: 'none'
					});
					return false;
				}
				if (this.formData.name == '') {
					wx.showToast({
						title: this.placeholder,
						icon: 'none'
					});
					return false;
				} else {
					var value = util.checkIDCardNum(this.formData.idCardNumber.trim());
					if (!value) {
						wx.showToast({
							title: "请填写正确的身份证号码",
							icon: 'none'
						});
						return false;
					}
				}
				if (this.formData.date == '') {
					wx.showToast({
						title: this.placeholderAd,
						icon: 'none'
					});
					return false;
				}
				// if (this.formData.phone == '') {
				//   wx.showToast({
				//       title: this.placeholderPh,
				//       icon: 'none'
				//   });
				//   return false;
				// }
				if (this.formData.phone) {
					var value = util.checkPhoneNum(this.formData.phone.trim());
					if (!value) {
						wx.showToast({
							title: "请填写正确的手机号码",
							icon: 'none'
						});
						return false;
					}
				}
				return true;
			}

		},

	}
</script>

<style scoped>
	.pageContent {
		background-color: #F3F6F9;
		padding: 20rpx 0rpx 0rpx 0rpx;
	}

	.memberTitle {
		font-size: 30rpx;
		font-weight: bold;
		color: #333333;
		line-height: 42rpx;
		padding: 30rpx 0rpx 20rpx 30rpx;
	}

	.memberMain {
		background-color: #FFFFFF;
		padding: 30rpx 30rpx 20rpx 30rpx;
	}

	.memberMaTi {
		color: #333333;
		line-height: 42rpx;
		font-size: 30rpx;
		padding: 0rpx 0rpx 10rpx 0rpx;
	}

	.memberType {
		display: inline-block;
		width: 150rpx;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 6rpx;
		text-align: center;
		border: 1rpx solid #E7E7E7;
	}

	.memberType.select {
		background-color: #7A71FF;
		color: #FFFFFF;
	}

	.memberType+.memberType {
		margin-left: 30rpx;
	}

	.memberType:nth-child(n+5) {
		margin-top: 20rpx;
	}

	.memberType:nth-child(4n+1) {
		margin-left: 0rpx;
	}

	.memberItem {
		display: flex;
		align-items: center;
		font-size: 30rpx;
		/* border: 1rpx solid #999999; */
	}

	.memberItSt {
		color: #FF6E5D;
	}

	.memberItSt.empty {
		color: #FFFFFF;
	}

	.memberItTi {
		width: 168rpx;
		color: #333333;
		margin-right: 36rpx;
		/* white-space: nowrap; */
		height: 40rpx;
		/* border: 1rpx solid coral; */
	}

	.memberRight {
		display: flex;
		height: 90rpx;
		width: 100%;
		align-items: center;
		border-bottom: 1rpx solid #E7E7E7;
		/* border: 1rpx solid darkgreen; */
	}

	.memberItIn {
		width: 88%;
		/* border: 1rpx solid #E7E7E7; */
	}

	.memberItIc {
		width: 35rpx;
		height: 30rpx;
		margin: 0rpx 10rpx 0rpx 20rpx;
	}

	.perType {
		display: inline-block;
		width: 90rpx;
		line-height: 45rpx;
		border-radius: 4rpx;
		text-align: center;
		margin-right: 20rpx;
		color: #70B7FF;
		background: #F2F8FF;
		border: 1rpx solid #B8DCFF;
	}

	.perType.select {
		background: #70B7FF;
		color: #FFFFFF;
	}

	.memberUpload {
		display: flex;
		width: 100%;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0rpx 20rpx 0rpx;
		border-bottom: 1rpx solid #E7E7E7;
	}

	.memberUpTrueIc {
		width: 230rpx;
		height: 152rpx;
	}

	.memberUpMain {
		position: relative;
		width: 230rpx;
		height: 152rpx;
	}

	.memberUpMainIm {
		position: absolute;
		width: 230rpx;
		height: 152rpx;
	}

	.memberUpMainIc {
		position: absolute;
		width: 44rpx;
		height: 36rpx;
	}

	.memberUpMainTe {
		position: absolute;
		height: 36rpx;
		line-height: 36rpx;
		font-size: 20rpx;
		color: #1086FF;
		margin-top: 50rpx;
		white-space: nowrap;
	}

	.memberUploadLea {
		display: flex;
		width: 100%;
		padding: 20rpx 0rpx 20rpx 0rpx;
		border-bottom: 1rpx solid #E7E7E7;
	}

	.memberUpLeaMa {
		display: inline-block;
		width: 124rpx;
		height: 84rpx;
	}

	.memberUpLeaMa:nth-child(n+2) {
		margin-left: 8rpx;
	}

	.memberUpLea {
		display: inline-block;
		width: 124rpx;
		height: 84rpx;
	}

	.comePicRight {
		position: relative;
		display: flex;
		height: 90rpx;
		width: 100%;
		align-items: center;
		border-bottom: 1rpx solid #E7E7E7;
	}

	.comePicLim {
		position: absolute;
		right: 0rpx;
		top: 26rpx;
		width: 35rpx;
		height: 30rpx;
		margin: 0rpx 0rpx 0rpx 0rpx;
	}

	.btOne {
		margin: 40rpx 0rpx 0rpx 0rpx;
	}

	.btDefault {
		opacity: 0.6;
	}

	.switchImg {
		height: 72rpx;
		width: 72rpx;
		margin-left: 10rpx;
	}
</style>
